package utilityPrograms;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;

import sun.applet.Main;

public class KillNotUsedIcons {


	private LinkedList<File> fileList = new LinkedList<File>();
	private LinkedList<File> images = new LinkedList<File>();



	public static void main (String[] args) {

		/*NOTE: Weather icons, Moods icons and Emoticons and indirectly referenced images are filtered;
		 * you have to add them manually.
		 */
		
		
		KillNotUsedIcons killer = new KillNotUsedIcons();
		killer.explore (new File ("src"));

		killer.searchImages();
		killer.killImages(new File ("images"));
	}




	public void explore (File f) {

		if (f.isDirectory()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) {
				explore (files[i]);
			}
		} else 
			fileList.add(f);
	}

	public void printFiles () {
		for (int i = 0; i < fileList.size(); i++) {
			System.out.println(fileList.get(i));
		}
	}

	public void find(File f) {
		Scanner in = null;
		try {
			in = new Scanner(new FileReader(f));
			while(in.hasNextLine()) {
				String line = in.nextLine();
				int start = line.indexOf("/images");
				int end;
				if (start != -1) {
					end = line.indexOf("\"", start);
					File nf = new File (line.substring(start+1, end));
					if (!nf.isDirectory())
						images.add(nf);
				}
			}
		}
		catch(IOException e) {
			e.printStackTrace();      
		} finally {
			try {
				in.close();
			} catch(Exception e) {
				/* ignore */
			}  
		}
	}

	public void searchImages () {
		for (int i = 0; i < fileList.size(); i++) {
			find(fileList.get(i));
		}
	}

	public void printImages () {
		for (int i = 0; i < images.size(); i++) {
			System.out.println(images.get(i));
		}
	}

	public void killImages (File file) {
		if (!file.isDirectory()) {
			boolean contained = false;
			for (int i = 0; i < images.size(); i++) {
				if (images.get(i).equals(file)) {
					System.out.println("Found: "+file);
					contained = true;
					break;
				}
			}
			if (contained == false){
				file.delete();
				System.out.println("Deleted: "+file);
			}
		}else {
			File[] files = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				killImages(files[i]);
			}
		}
	}
}
